package com.stylefeng.guns.modular.apple.utils;

import com.jcraft.jsch.*;
import com.stylefeng.guns.modular.apple.properties.SftpProperties;
import org.apache.commons.lang3.StringUtils;

import java.io.*;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.Vector;

/**
 * Sftp工具类
 */
public class SftpUtil {

    private Session session = null;
    private ChannelSftp channel = null;

    public SftpUtil(SftpProperties sftpProperties) throws JSchException {
        connectServer(sftpProperties);
    }

    /**
     * 连接sftp服务器
     *
     * @throws SocketException
     * @throws IOException
     * @throws JSchException
     */
    private void connectServer(SftpProperties sftpProperties) throws JSchException {
        JSch jsch = new JSch();
        // 根据用户名，主机ip，端口获取一个Session对象
        session = jsch.getSession(sftpProperties.getUserName(), sftpProperties.getIp(), sftpProperties.getPort());
        // 设置密码
        session.setPassword(sftpProperties.getPassword());
        // 为Session对象设置properties
        Properties config = new Properties();
        config.put("StrictHostKeyChecking", "no");
        session.setConfig(config);
        // 通过Session建立链接
        session.connect();
        // 打开SFTP通道
        channel = (ChannelSftp) session.openChannel("sftp");
        // 建立SFTP通道的连接
        channel.connect();
    }

    /**
     * 自动关闭资源
     */
    public void close() {
        if (channel != null) {
            channel.disconnect();
        }
        if (session != null) {
            session.disconnect();
        }
    }

    public List<ChannelSftp.LsEntry> getDirList(String path) throws SftpException {
        List<ChannelSftp.LsEntry> list = new ArrayList<>();
        if (channel != null) {
            Vector vv = channel.ls(path);
            if (vv == null && vv.size() == 0) {
                return list;
            } else {
                Object[] aa = vv.toArray();
                for (int i = 0; i < aa.length; i++) {
                    ChannelSftp.LsEntry temp = (ChannelSftp.LsEntry) aa[i];
                    list.add(temp);

                }
            }
        }
        return list;
    }

    /**
     * 下载文件
     *
     * @param remotePathFile 远程文件
     * @param localPathFile  本地文件[绝对路径]
     * @throws SftpException SftpException
     * @throws IOException   IOException
     */
    public void downloadFile(String remotePathFile, String localPathFile) throws SftpException, IOException {
        try (FileOutputStream os = new FileOutputStream(new File(localPathFile))) {
            if (channel == null)
                throw new IOException("sftp server not login");
            channel.get(remotePathFile, os);
        }
    }

    /**
     * 上传文件
     *
     * @param remoteFile 远程文件
     * @param localFile  本地文件
     * @throws SftpException
     * @throws IOException
     */
    public void uploadFile(String remoteFile, String localFile) throws SftpException, IOException {
        try (FileInputStream in = new FileInputStream(new File(localFile))) {
            if (channel == null)
                throw new IOException("sftp server not login");
            channel.put(in, remoteFile);
        }
    }

    /**
     * 上传文件
     *
     * @param remoteFile
     * @param inputStream
     * @throws SftpException
     * @throws IOException
     */
    public void uploadFile(String remoteFile, InputStream inputStream) throws SftpException, IOException {
        if (channel == null)
            throw new IOException("sftp server not login");
        channel.put(inputStream, remoteFile);
    }

    /**
     * 删除文件
     *
     * @param directory  要删除文件所在目录
     * @param deleteFile 要删除的文件
     */
    public void delete(String directory, String deleteFile) throws SftpException {
        channel.cd(directory);
        SftpATTRS sftpATTRS = null;
        try {
            sftpATTRS = channel.stat(deleteFile);
        } catch (Exception e) {

        }
        if (sftpATTRS != null) {
            channel.rm(deleteFile);
        }
    }

    /**
     * 判断图片格式
     *
     * @param contentType
     * @return
     */
    public static boolean isImages(String contentType) {
        return "image/jpeg".equals(contentType) || "image/png".equals(contentType) || "image/gif".equals(contentType);
    }

    public static String getExtName(String fileName) {
        if (StringUtils.isEmpty(fileName))
            return null;
        return fileName.substring(fileName.lastIndexOf("."));
    }

    /**
     * 判断子目录文件夹是否存在，不存在即创建
     *
     * @param path
     * @param folderName
     */
    public void mkdir(String path, String folderName) throws SftpException {
        channel.cd(path);
        SftpATTRS sftpATTRS = null;
        try {
            sftpATTRS = channel.stat(folderName);
        } catch (Exception e) {

        }
        if (sftpATTRS == null) {
            channel.mkdir(folderName);
        }
    }

}
